<template>
  <van-popup v-model:show="showPicker" round position="bottom">
    <van-picker
      :columns="projectList"
      :columns-field-names="customFieldName"
      @confirm="onConfirm"
      @cancel="showPicker = false"
    >
      <template #title>
        <span class="clear-btn" @click="handleClear"> 清空选择 </span>
      </template>
    </van-picker>
  </van-popup>
</template>

<script setup lang="ts">
import {
  ref,
  defineProps,
  computed,
  defineEmits,
  onMounted,
  watch,
  watchEffect,
  Ref,
} from 'vue'
import { getCensusList, getList } from '../api'
import { Project } from '/@/types/Project'
import { useLoginer } from '/@/use/loginer'

interface PropsType {
  visible: boolean
  modelValue: Project | null
}
const props = defineProps<PropsType>()

const emit = defineEmits(['update:visible', 'update:modelValue', 'onItemClick'])

const showPicker = computed<boolean>({
  get() {
    return props.visible
  },
  set(val) {
    emit('update:visible', val)
  },
})

const { projectList } = usProjectList(showPicker)

function usProjectList(showPicker: Ref<boolean>) {
  const projectList = ref<Project[]>([])
  const { loginer } = useLoginer()
  watchEffect(async () => {
    if (!loginer.value?.tenantId) {
      return
    }
    if (!showPicker.value) {
      return
    }
    const {
      data: {
        data: { records },
      },
    } = await getCensusList(1, 1000, { tenantId: loginer.value.tenantId })
    projectList.value = records
  })
  return { projectList }
}

const customFieldName = {
  text: 'projectName',
}

const value = computed<Project | null>({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  },
})

function onConfirm(item: Project) {
  showPicker.value = false
  value.value = item
}

function handleClear() {
  showPicker.value = false
  value.value = null
}
</script>

<style lang="less" scoped>
.clear-btn {
  font-size: var(--van-picker-action-font-size);
}
</style>
